//
//  BKBubbleView.m
//  BESTKEEP
//
//  Created by Canny on 2016/10/24.
//  Copyright © 2016年 YISHANG. All rights reserved.
//

#import "BKBubbleView.h"
#import "WkSpringLayerAnimation.h"

@implementation BKBubbleView{
    
    UIBezierPath *cutePath;
    UIColor *fillColorForCute;
    UIDynamicAnimator *animator;
    UISnapBehavior  *snap;
    
    UIView *backView;
    CGFloat r1;
    CGFloat r2;
    CGFloat x1;
    CGFloat y1;
    CGFloat x2;
    CGFloat y2;
    CGFloat centerDistance;
    CGFloat cosDigree;
    CGFloat sinDigree;
    
    CGPoint pointA; //A
    CGPoint pointB; //B
    CGPoint pointD; //D
    CGPoint pointC; //C
    CGPoint pointO; //O
    CGPoint pointP; //P
    
    CGRect oldBackViewFrame;
    CGPoint initialPoint; //起始的中心点
    CGPoint oldBackViewCenter;
    CAShapeLayer *shapeLayer;
    
}

-(id)initWithPoint:(CGPoint)point superView:(UIView *)view{
    self = [super initWithFrame:CGRectMake(point.x, point.y, self.bubbleWidth, self.bubbleWidth)];
    if(self){
        initialPoint = point;
        self.containerView = view;
        [self.containerView addSubview:self];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUp];
    }
    return self;
}

-(void)setUp{
    
    shapeLayer = [CAShapeLayer layer];
    self.backgroundColor = [UIColor clearColor];
    self.frontView = [[UIView alloc]initWithFrame:CGRectMake(initialPoint.x,initialPoint.y, self.bubbleWidth, self.bubbleWidth)];
    
    r2 = self.frontView.bounds.size.width / 2;
    self.frontView.layer.cornerRadius = r2;
            self.frontView.backgroundColor = self.bubbleColor;
    
    backView = [[UIView alloc]initWithFrame:self.frontView.frame];
    r1 = backView.bounds.size.width / 2;
    backView.layer.cornerRadius = r1;
        backView.backgroundColor = self.bubbleColor;
    
    [self.containerView addSubview:backView];
    [self.containerView addSubview:self.frontView];
    
    x1 = backView.center.x;
    y1 = backView.center.y;
    x2 = self.frontView.center.x;
    y2 = self.frontView.center.y;
    
    pointA = CGPointMake(x1-r1,y1);   // A
    pointB = CGPointMake(x1+r1, y1);  // B
    pointD = CGPointMake(x2-r2, y2);  // D
    pointC = CGPointMake(x2+r2, y2);  // C
    pointO = CGPointMake(x1-r1,y1);   // O
    pointP = CGPointMake(x2+r2, y2);  // P
    
    oldBackViewFrame  = backView.frame;
    oldBackViewCenter = backView.center;
    
    backView.hidden = YES;//为了看到 frontView 的气泡晃动效果，需要暂时隐藏 backView
    [self addAniamtionLikeGameCenterBubble];
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handleDragGesture:)];
    [self.frontView addGestureRecognizer:pan];
}


-(void)drawRect{
    x1 = backView.center.x;
    y1 = backView.center.y;
    x2 = self.frontView.center.x;
    y2 = self.frontView.center.y;
    
    centerDistance = sqrtf((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
    if (centerDistance == 0) {
        cosDigree = 1;
        sinDigree = 0;
    }else{
        cosDigree = (y2-y1)/centerDistance;
        sinDigree = (x2-x1)/centerDistance;
    }
    
    r1 = oldBackViewFrame.size.width / 2 - centerDistance/self.viscosity;
    
    pointA = CGPointMake(x1-r1*cosDigree, y1+r1*sinDigree);  // A
    pointB = CGPointMake(x1+r1*cosDigree, y1-r1*sinDigree);  // B
    pointD = CGPointMake(x2-r2*cosDigree, y2+r2*sinDigree);  // D
    pointC = CGPointMake(x2+r2*cosDigree, y2-r2*sinDigree);  // C
    pointO = CGPointMake(pointA.x + (centerDistance / 2)*sinDigree, pointA.y + (centerDistance / 2)*cosDigree);
    pointP = CGPointMake(pointB.x + (centerDistance / 2)*sinDigree, pointB.y + (centerDistance / 2)*cosDigree);
    
    backView.center = oldBackViewCenter;
    backView.bounds = CGRectMake(0, 0, r1*2, r1*2);
    backView.layer.cornerRadius = r1;
    
    cutePath = [UIBezierPath bezierPath];
    [cutePath moveToPoint:pointA];
    [cutePath addQuadCurveToPoint:pointD controlPoint:pointO];
    [cutePath addLineToPoint:pointC];
    [cutePath addQuadCurveToPoint:pointB controlPoint:pointP];
    [cutePath moveToPoint:pointA];
    
    if (backView.hidden == NO) {
        shapeLayer.path = [cutePath CGPath];
        shapeLayer.fillColor = [fillColorForCute CGColor];
        /*
         * //将一个子layer插入到最下面
         - (void)insertSublayer:(CALayer *)layer below:(nullable CALayer *)sibling;
         */
        [self.containerView.layer insertSublayer:shapeLayer below:self.frontView.layer];
    }
    
}


-(void)handleDragGesture:(UIPanGestureRecognizer *)ges{
    CGPoint dragPoint = [ges locationInView:self.containerView];
    
    if (ges.state == UIGestureRecognizerStateBegan) {
        backView.hidden = NO;
        fillColorForCute = self.bubbleColor;
        [self RemoveAniamtionLikeGameCenterBubble];
    }else if (ges.state == UIGestureRecognizerStateChanged){
        self.frontView.center = dragPoint;
        if (r1 <= 6) {
            fillColorForCute = [UIColor clearColor];
            backView.hidden = YES;
            [shapeLayer removeFromSuperlayer];
        }
        [self drawRect];
    } else if (ges.state == UIGestureRecognizerStateEnded || ges.state ==UIGestureRecognizerStateCancelled || ges.state == UIGestureRecognizerStateFailed){
        
        backView.hidden = YES;
        fillColorForCute = [UIColor clearColor];
        [shapeLayer removeFromSuperlayer];
        [UIView animateWithDuration:0.5 delay:0.0f usingSpringWithDamping:0.4f initialSpringVelocity:0.0f options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.frontView.center = oldBackViewCenter;
        } completion:^(BOOL finished) {
            if (finished) {
                [self addAniamtionLikeGameCenterBubble];
            }
        }];
    }
    
}


//---- 类似GameCenter的气泡晃动动画 ------
-(void)addAniamtionLikeGameCenterBubble {
    
    NSArray * arr_values=@[@[@1.23, @0.92, @1.24], @[@0.91, @1.26, @0.98], @[@1.27, @1.05, @1.21], @[@0.95, @1.24, @1.05], @[@1.24, @1.04, @1.22], @[@0.95, @1.17, @0.98], @[@1.26, @1.07, @1.13], @[@0.93, @1.12, @1.05], @[@1.25, @1.04, @1.25], @[@0.91, @1.25, @1.02]];
    NSArray * arr_keyTimes=@[@[@0.0, @0.43, @1.0], @[@0.0, @0.60, @1.0], @[@0.0, @0.66, @1.0], @[@0.0, @0.55, @1.0], @[@0.0, @0.45, @1.0], @[@0.0, @0.43, @1.0], @[@0.0, @0.56, @1.0], @[@0.0, @0.59, @1.0], @[@0.0, @0.50, @1.0], @[@0.0, @0.48, @1.0]];
    
    int index = (arc4random() % 10);
    NSArray * arr_value=arr_values[index];
    NSArray * arr_keyTime=arr_keyTimes[index];
 
    CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    pathAnimation.calculationMode = kCAAnimationPaced;
    pathAnimation.fillMode = kCAFillModeForwards;
    pathAnimation.removedOnCompletion = NO;
    pathAnimation.repeatCount = INFINITY;
    pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    pathAnimation.duration = 5.0;
    
    CGMutablePathRef curvedPath = CGPathCreateMutable();
    CGRect circleContainer = CGRectInset(self.frontView.frame, self.frontView.bounds.size.width / 2 - 3, self.frontView.bounds.size.width / 2 - 3);
    CGPathAddEllipseInRect(curvedPath, NULL, circleContainer);
    
    pathAnimation.path = curvedPath;
    CGPathRelease(curvedPath);
    [self.frontView.layer addAnimation:pathAnimation forKey:@"myCircleAnimation"];
    
    CAKeyframeAnimation *scaleX = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale.x"];
    scaleX.duration = 1;

    scaleX.values = arr_value;
    scaleX.keyTimes = arr_keyTime;
    scaleX.repeatCount = INFINITY;
    scaleX.autoreverses = YES;
    
    scaleX.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [self.frontView.layer addAnimation:scaleX forKey:@"scaleXAnimation"];
    
    
    CAKeyframeAnimation *scaleY = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale.y"];
    scaleY.duration = 1.5;
    scaleY.values = arr_value;
    scaleY.keyTimes = arr_keyTime;
    scaleY.repeatCount = INFINITY;
    scaleY.autoreverses = YES;
    scaleY.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [self.frontView.layer addAnimation:scaleY forKey:@"scaleYAnimation"];
    
    
}

#pragma mark-气泡无规则运动
-(void)bubble_Random_MoveWithTag:(int )tag{
    CAKeyframeAnimation *anim = [[WkSpringLayerAnimation sharedAnimManager]
                        Line_Move_Anima:@"position" duration:2.5 CenterPoint:[self point_bubbleWithTag:tag] withTag:tag];
    [self.frontView.layer addAnimation:anim forKey:@"position"];
}
#pragma mark========================================================================

#pragma mark========================================================================


-(void)dismiss_BubbleWithTag:(int)tag{
    CGFloat HH=(ScreenWidth*430.0/750.0+ScreenWidth*243/1125.0-85.0)/2.0;
    CAKeyframeAnimation *animation_rise_1 = [self Move_Anima:@"position" duration:0.5f fromValue:[self point_bubbleWithTag:tag] toValue:CGPointMake(ScreenWidth/2.0,HH)];
    [self.frontView.layer addAnimation:animation_rise_1 forKey:nil];
    CAKeyframeAnimation *animation_transform_1 = [self transform_Anima:@"transform.scale" duration:0.5f fromValue:@(1.00) toValue:@(0.01)];
    [self.frontView.layer addAnimation:animation_transform_1 forKey:nil];
    
}


- (CAKeyframeAnimation *)Move_Anima:(NSString *)keypath
                           duration:(CFTimeInterval)duration
                          fromValue:(CGPoint)fromValue
                            toValue:(CGPoint)toValue{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
    animation.keyPath = keypath;
    //    animation.repeatCount=MAXFLOAT;
    animation.repeatCount=1;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.duration = duration;
    animation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    //    animation.delegate=self;
    animation.values =
    [self basicAnimationValues:fromValue toValue:toValue duration:duration];
    return animation;
}
-(NSMutableArray *)basicAnimationValues:(CGPoint)fromValue toValue:(CGPoint)toValue duration:(CGFloat)duration {
    
    NSInteger numOfFrames = duration * 60;
    NSMutableArray *values = [NSMutableArray arrayWithCapacity:numOfFrames];
    for (NSInteger i = 0; i < numOfFrames; i++) {
        [values addObject:[NSValue valueWithCGPoint:CGPointMake(200, 200)]];
    }
    //    CGFloat diffX = ABS(toValue.x - fromValue.x );
    //    CGFloat diffY = ABS(toValue.y - fromValue.y );
    CGFloat diffX = toValue.x - fromValue.x ;
    CGFloat diffY = toValue.y - fromValue.y ;
    for (NSInteger frame = 0; frame < numOfFrames; frame++) {
        CGFloat diff_count = (CGFloat)frame / (CGFloat)numOfFrames;
        CGFloat value_X = fromValue.x + diffX * diff_count;
        CGFloat value_Y = fromValue.y + diffY * diff_count;
        NSValue *value_point=[NSValue valueWithCGPoint:CGPointMake(value_X, value_Y)];
        values[frame] = value_point;
    }
    return values;
    
    
}

/*
 * 关键帧缩放
 */
- (CAKeyframeAnimation *)transform_Anima:(NSString *)keypath
                                duration:(CFTimeInterval)duration
                               fromValue:(id)fromValue
                                 toValue:(id)toValue{
    
    
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
    animation.keyPath = keypath;
    //    animation.repeatCount=MAXFLOAT;
    animation.repeatCount=1;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.duration = duration;
    animation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.delegate=self;
    animation.values =
    [self transform_basicAnimationValues:fromValue toValue:toValue duration:duration];
    return animation;
    
}

-(NSMutableArray *)transform_basicAnimationValues:(id)fromValue toValue:(id)toValue duration:(CGFloat)duration {
    
    NSInteger numOfFrames = duration * 60;
    NSMutableArray *values = [NSMutableArray arrayWithCapacity:numOfFrames];
    for (NSInteger i = 0; i < numOfFrames; i++) {
        [values addObject:@(0.0)];
    }
    CGFloat diff = [toValue floatValue] - [fromValue floatValue];
    for (NSInteger frame = 0; frame < numOfFrames; frame++) {
        
        CGFloat x = (CGFloat)frame / (CGFloat)numOfFrames;
        CGFloat value = [fromValue floatValue] + diff * x;
        values[frame] = @(value);
    }
    return values;
    
}
-(void)RemoveAniamtionLikeGameCenterBubble {
    [self.frontView.layer removeAllAnimations];
}

/*
 * 获取气泡坐标
 */
-(CGPoint )point_bubbleWithTag:(int)tag{
    CGPoint  point_bubble;
    
    if (tag==1) {
        /*
         * 左上   (SCREEN_WIDTH/2.0-50,SC)
         */
        if (ScreenWidth>376) {
            point_bubble=CGPointMake(ScreenWidth/2.0-50, 50+15);
        }else{
            point_bubble=CGPointMake(ScreenWidth/2.0-50, 50);
        }
        
        //        if (SCREEN_WIDTH>376) {//ip_6P
        //            point_bubble=CGPointMake(SCREEN_WIDTH/2.0-50, 50+15);
        //        }else if(SCREEN_WIDTH>370){//ip_6
        //            point_bubble=CGPointMake(SCREEN_WIDTH/2.0-50, 50);
        //        }else{//ip_5
        //
        //        }
        
    }else if(tag==2){
        /*
         * 左下
         */
        if (ScreenWidth>376) {
            point_bubble=CGPointMake(ScreenWidth/2.0-50, 125+15);
        }else{
            point_bubble = CGPointMake(ScreenWidth/2.0-50, 125);
        }
        //        if (SCREEN_WIDTH>376) {//ip_6P
        //            point_bubble=CGPointMake(SCREEN_WIDTH/2.0-50, 125+15);
        //        }else if(SCREEN_WIDTH>370){//ip_6
        //            point_bubble = CGPointMake(SCREEN_WIDTH/2.0-50, 125);
        //        }else{//ip_5
        //
        //        }
    }else if(tag==3){
        
        /*
         * 右上
         */
        if (ScreenWidth>376) {
            point_bubble = CGPointMake(ScreenWidth/2.0+40, 60+15);
        }else{
            point_bubble = CGPointMake(ScreenWidth/2.0+40, 60);
        }
        //        if (SCREEN_WIDTH>376) {//ip_6P
        //            point_bubble = CGPointMake(SCREEN_WIDTH/2.0+40, 60+15);
        //        }else if(SCREEN_WIDTH>370){//ip_6
        //            point_bubble = CGPointMake(SCREEN_WIDTH/2.0+40, 60);
        //        }else{//ip_5
        //
        //        }
        
    }else if(tag==4){
        /*
         * 右下
         */
        if (ScreenWidth>376) {
            point_bubble = CGPointMake(ScreenWidth/2.0+45, 135+15) ;
        }else{
            point_bubble =CGPointMake(ScreenWidth/2.0+45, 135);
        }
        //        if (SCREEN_WIDTH>376) {//ip_6P
        //            point_bubble = CGPointMake(SCREEN_WIDTH/2.0+45, 135+15) ;
        //        }else if(SCREEN_WIDTH>370){//ip_6
        //            point_bubble =CGPointMake(SCREEN_WIDTH/2.0+45, 135);
        //        }else{//ip_5
        //            
        //        }
    }
    
    return point_bubble;
}

@end













































